package com.dd.service;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.dd.model.PublicSupervisionData;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate; // 导入 LocalDate
import java.time.format.DateTimeFormatter; // 导入 DateTimeFormatter
import java.time.format.DateTimeParseException; // 导入 DateTimeParseException
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator; // 导入 Comparator
import java.util.LinkedHashMap; // 导入 LinkedHashMap
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors; // 导入 Collectors

public class PublicDataService {
    private static final String DATA_FILE_PATH = "public_supervision_data.json";
    private static final String RESOURCES_DATA_FILE = "public_supervision_data.json";
    private List<PublicSupervisionData> publicSupervisionDataList;
    private Gson gson;

    public PublicDataService() {
        gson = new GsonBuilder().setPrettyPrinting().create();
        publicSupervisionDataList = new ArrayList<>();
        loadPublicData();
    }

    // 初始化模拟数据（仅在第一次运行时生成，或文件不存在时）
    public void initializeMockData() {
        // 检查文件是否存在，如果不存在或者内容为空才初始化模拟数据
        File dataFile = new File(DATA_FILE_PATH);
        if (!dataFile.exists() || publicSupervisionDataList.isEmpty()) { // 注意：这里可能需要调整逻辑。如果文件存在但您想强制更新模拟数据，可以暂时删除 `dataFile.exists()` 判断或手动删除文件。
            System.out.println("Initializing mock data for Public Supervision.");
            publicSupervisionDataList.clear(); // 清除现有数据，确保重新初始化

            // 使用完整的构造方法初始化数据
            publicSupervisionDataList.add(new PublicSupervisionData("P001", "2023-01-01", "辽宁省沈阳市和平区青年大街1号", "辽宁省", "沈阳市", "空气污染", "中", "小区附近工厂排放废气，有异味。", "已提交", "", "", "良", "张三丰", "", ""));
            publicSupervisionDataList.add(new PublicSupervisionData("P002", "2023-01-05", "辽宁省大连市沙河口区星海广场", "辽宁省", "大连市", "噪音污染", "高", "建筑工地夜间施工，噪音扰民。", "已指派", "GW001", "张三", "轻度污染", "李小龙", "", ""));
            publicSupervisionDataList.add(new PublicSupervisionData("P003", "2023-01-10", "吉林省长春市朝阳区解放大路", "吉林省", "长春市", "水体污染", "低", "河道漂浮物增多，水质浑浊。", "已完成", "GW002", "李四", "优", "王昭君", "", ""));
            publicSupervisionDataList.add(new PublicSupervisionData("P004", "2023-01-12", "黑龙江省哈尔滨市南岗区中山路", "黑龙江省", "哈尔滨市", "固体废弃物", "中", "生活垃圾随意堆放，影响环境。", "已驳回", "GW003", "王五", "中度污染", "赵子龙", "", ""));
            publicSupervisionDataList.add(new PublicSupervisionData("P005", "2023-01-15", "辽宁省沈阳市铁西区兴华街", "辽宁省", "沈阳市", "空气污染", "高", "工厂烟囱冒黑烟，气味刺鼻。", "已提交", "", "", "重度污染", "孙悟空", "", ""));
            // 更多模拟数据，特别是要有不同月份的AQI数据，用于趋势分析
            publicSupervisionDataList.add(new PublicSupervisionData("P006", "2023-02-01", "辽宁省沈阳市浑南区", "辽宁省", "沈阳市", "噪音污染", "中", "施工噪音大。", "已提交", "", "", "优", "刘备", "", ""));
            publicSupervisionDataList.add(new PublicSupervisionData("P007", "2023-02-10", "辽宁省大连市高新园区", "辽宁省", "大连市", "工业废气", "高", "工厂排放刺激性气体。", "已指派", "GW004", "赵六", "轻度污染", "关羽", "", ""));
            publicSupervisionDataList.add(new PublicSupervisionData("P008", "2023-03-05", "吉林省吉林市船营区", "吉林省", "吉林市", "水体污染", "低", "湖水有异味。", "已完成", "GW001", "张三", "良", "曹操", "", ""));
            publicSupervisionDataList.add(new PublicSupervisionData("P009", "2023-03-15", "黑龙江省齐齐哈尔市龙沙区", "黑龙江省", "齐齐哈尔市", "固体废弃物", "中", "垃圾分类不规范。", "已驳回", "GW002", "李四", "中度污染", "诸葛亮", "", ""));
            publicSupervisionDataList.add(new PublicSupervisionData("P010", "2023-04-01", "辽宁省鞍山市铁西区", "辽宁省", "鞍山市", "空气污染", "中", "汽车尾气污染严重。", "已提交", "", "", "轻度污染", "周瑜", "", ""));
            publicSupervisionDataList.add(new PublicSupervisionData("P011", "2023-04-10", "辽宁省抚顺市望花区", "辽宁省", "抚顺市", "噪音污染", "高", "KTV夜间扰民。", "已指派", "GW003", "王五", "中度污染", "貂蝉", "", ""));
            publicSupervisionDataList.add(new PublicSupervisionData("P012", "2023-05-01", "吉林省四平市铁西区", "吉林省", "四平市", "水体污染", "低", "农田灌溉水污染。", "已完成", "GW004", "赵六", "良", "鲁智深", "", ""));
            publicSupervisionDataList.add(new PublicSupervisionData("P013", "2023-05-10", "黑龙江省牡丹江市东安区", "黑龙江省", "牡丹江市", "固体废弃物", "中", "建筑垃圾乱倒。", "已驳回", "GW001", "张三", "优", "林冲", "", ""));


            savePublicData(); // 初始化后保存数据
        }
    }

    public List<PublicSupervisionData> getAllPublicSupervisionData() {
        return new ArrayList<>(publicSupervisionDataList);
    }

    /**
     * 更新公众监督数据
     * @param updatedData 包含更新信息的PublicSupervisionData对象
     * @return true if update successful, false otherwise
     */
    public boolean updatePublicData(PublicSupervisionData updatedData) {
        for (int i = 0; i < publicSupervisionDataList.size(); i++) {
            if (publicSupervisionDataList.get(i).getId().equals(updatedData.getId())) {
                publicSupervisionDataList.set(i, updatedData);
                savePublicData(); // 更新后保存数据
                System.out.println("DEBUG: Data updated in service: " + updatedData);
                return true;
            }
        }
        return false;
    }

    /**
     * 获取所有网格员列表。
     * @return 网格员姓名列表
     */
    public List<String> getAllGridWorkers() {
        // 在实际应用中，这应该从另一个服务或数据库获取
        List<String> workers = new ArrayList<>();
        workers.add("张三");
        workers.add("李四");
        workers.add("王五");
        workers.add("赵六");
        workers.add("陈明");
        workers.add("王芳");
        return workers;
    }

    /**
     * 获取AQI等级分布统计数据。
     * 结果是一个Map，键是AQI等级（String），值是该等级的数据条数（Long）。
     * 会过滤掉estimatedAqi为空或空白的数据。
     * @return AQI等级及其对应数量的Map
     */
    public Map<String, Long> getAqiDistributionStatistics() {
        return publicSupervisionDataList.stream()
                .map(PublicSupervisionData::getEstimatedAqi)
                .filter(aqi -> aqi != null && !aqi.trim().isEmpty())
                .collect(Collectors.groupingBy(aqi -> aqi, Collectors.counting()));
    }

    /**
     * 将AQI等级映射到数值，用于趋势统计。
     * @param aqiLevel AQI等级字符串
     * @return 对应的数值，如果无法识别则返回0
     */
    private int mapAqiLevelToValue(String aqiLevel) {
        if (aqiLevel == null || aqiLevel.trim().isEmpty()) {
            return 0; // 或者一个表示无效的值
        }
        switch (aqiLevel.trim()) {
            case "优": return 1;
            case "良": return 2;
            case "轻度污染": return 3;
            case "中度污染": return 4;
            case "重度污染": return 5;
            case "严重污染": return 6;
            default: return 0; // 未知等级
        }
    }

    /**
     * 获取AQI趋势统计数据（按月份平均AQI值）。
     * 结果是一个Map，键是月份（格式为YYYY-MM），值是该月份的平均AQI数值。
     * @return 按月份分组的平均AQI数值Map
     */
    public Map<String, Double> getAqiTrendStatisticsByMonth() {
        Map<String, Double> trendData = publicSupervisionDataList.stream()
                .filter(data -> data.getEstimatedAqi() != null && !data.getEstimatedAqi().trim().isEmpty())
                .collect(Collectors.groupingBy(
                        data -> {
                            try {
                                // 假设 submitDate 格式是 "YYYY-MM-DD"
                                LocalDate date = LocalDate.parse(data.getSubmitDate());
                                return date.format(DateTimeFormatter.ofPattern("yyyy-MM"));
                            } catch (DateTimeParseException e) {
                                // 如果日期格式不正确，则返回一个默认或无效的月份
                                System.err.println("Error parsing date: " + data.getSubmitDate() + " for trend statistics. " + e.getMessage());
                                return "Invalid Date";
                            }
                        },
                        Collectors.averagingInt(data -> mapAqiLevelToValue(data.getEstimatedAqi()))
                ));

        // 过滤掉无效日期，并按月份字符串排序（自然排序即可）
        return trendData.entrySet().stream()
                .filter(entry -> !entry.getKey().equals("Invalid Date"))
                .sorted(Map.Entry.comparingByKey()) // 按月份字符串自然排序，例如 "2023-01" < "2023-02"
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue,
                        LinkedHashMap::new // 保持排序后的顺序
                ));
    }

    /**
     * 根据查询条件过滤数据
     * @param queryText 查询文本（匹配ID、地址、问题类型）
     * @param selectedStatus 选中的状态（如果为null或空，则不作为过滤条件）
     * @return 过滤后的数据列表
     */
    public List<PublicSupervisionData> searchSupervisionData(String queryText, String selectedStatus) {
        List<PublicSupervisionData> filteredList = getAllPublicSupervisionData();

        if (queryText != null && !queryText.trim().isEmpty()) {
            String lowerCaseQuery = queryText.trim().toLowerCase();
            filteredList = filteredList.stream()
                    .filter(data -> data.getId().toLowerCase().contains(lowerCaseQuery) ||
                            data.getSpecificAddress().toLowerCase().contains(lowerCaseQuery) ||
                            data.getProblemType().toLowerCase().contains(lowerCaseQuery))
                    .collect(Collectors.toList());
        }

        if (selectedStatus != null && !selectedStatus.isEmpty() && !selectedStatus.equals("所有状态")) {
            filteredList = filteredList.stream()
                    .filter(data -> data.getStatus().equals(selectedStatus))
                    .collect(Collectors.toList());
        }
        return filteredList;
    }

    /**
     * 获取所有可用的状态列表
     * @return 状态列表
     */
    public List<String> getAllStatuses() {
        // 可以根据实际业务逻辑从数据中提取，或预定义
        return Arrays.asList("所有状态", "已提交", "已指派", "已完成", "已驳回");
    }

    /**
     * 获取所有省份列表
     * @return 省份列表
     */
    public Set<String> getAllProvinces() {
        return publicSupervisionDataList.stream()
                .map(PublicSupervisionData::getProvince)
                .collect(Collectors.toSet());
    }

    /**
     * 获取某个省份的所有城市列表
     * @param provinceName 省份名称
     * @return 城市列表
     */
    public Set<String> getCitiesByProvince(String provinceName) {
        return publicSupervisionDataList.stream()
                .filter(data -> data.getProvince().equals(provinceName))
                .map(PublicSupervisionData::getCity)
                .collect(Collectors.toSet());
    }

    // 将数据保存到JSON文件
    private void savePublicData() {
        try (FileWriter writer = new FileWriter(DATA_FILE_PATH)) {
            gson.toJson(publicSupervisionDataList, writer);
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Error saving public supervision data: " + e.getMessage());
        }
    }

    // 从JSON文件加载数据
    private void loadPublicData() {
        // 首先尝试从 resources 目录读取
        try {
            InputStream is = PublicDataService.class.getClassLoader()
                    .getResourceAsStream(RESOURCES_DATA_FILE);
            if (is != null) {
                InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
                Type listType = new TypeToken<ArrayList<PublicSupervisionData>>(){}.getType();
                List<PublicSupervisionData> loadedData = gson.fromJson(reader, listType);
                if (loadedData != null) {
                    publicSupervisionDataList = loadedData;
                    System.out.println("成功从 resources 目录加载了 " + publicSupervisionDataList.size() + " 条公众监督数据");
                }
                reader.close();
                is.close();
                return;
            }
        } catch (Exception e) {
            System.err.println("从 resources 目录读取 JSON 文件失败: " + e.getMessage());
        }

        // 如果从 resources 读取失败，尝试从当前目录读取
        try {
            File dataFile = new File(DATA_FILE_PATH);
            if (dataFile.exists() && dataFile.length() > 0) { // 检查文件是否存在且不为空
                try (FileReader reader = new FileReader(DATA_FILE_PATH)) {
                    Type listType = new TypeToken<ArrayList<PublicSupervisionData>>(){}.getType();
                    publicSupervisionDataList = gson.fromJson(reader, listType);
                    if (publicSupervisionDataList == null) {
                        publicSupervisionDataList = new ArrayList<>();
                    }
                    System.out.println("成功从当前目录加载了 " + publicSupervisionDataList.size() + " 条公众监督数据");
                }
            } else {
                System.out.println("Data file does not exist or is empty. Mock data will be initialized on next run.");
                // 这里不再直接调用initializeMockData，而是依靠App.java在启动时调用
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Error loading public supervision data: " + e.getMessage());
            publicSupervisionDataList = new ArrayList<>(); // 确保列表不为null
        } catch (com.google.gson.JsonSyntaxException e) {
            System.err.println("Error parsing JSON data (corrupted file?): " + e.getMessage());
            e.printStackTrace();
            publicSupervisionDataList = new ArrayList<>(); // JSON解析错误时也重置列表
        }
    }
}
